//
//  SXProgressImageView.swift
//  weibo.009
//
//  Created by mac on 15/9/21.
//  Copyright © 2015年 itcast. All rights reserved.
//

import UIKit

class SXProgressImageView: UIImageView {
    var progress: CGFloat = 0 {
        didSet{
            progressView.progress = progress
        }
    }
   
    private lazy var progressView: SXProgressView = {
        let p = SXProgressView()
       
        /// 清楚颜色
        p.backgroundColor = UIColor.clearColor()
        //添加控件
        self.addSubview(p)
        //设置代销
        p.frame = self.bounds
        
        return p
    }()
    
    /// 在 imageView 中，drawRect 函数不会被调用到
    //    override func drawRect(rect: CGRect) {
    //        // Drawing code
    //        printLog("come here")
    //    }
    
    /// 类中类，专供 HMProgressImageView 使用,这种方法只有在swift中才有
    private class SXProgressView:UIView{
    /// 进度数组 0 ~ 1
        var progress: CGFloat = 0{
            didSet{
                setNeedsDisplay()
            }
        }
        private override func drawRect(rect: CGRect) {
            if progress >= 1{
                return
            }
            //绘制曲线
            /**
            1.中心店
            2.半径
            3.起始角度
            4.结束角度
            5.是否逆时针
            
            self.center 是相对父视图
            */
            let center = CGPoint(x: rect.width * 0.5, y: rect.height * 0.5)
            let r = min(rect.width, rect.height) * 0.5
          
            let start = -CGFloat(M_PI_2)
            let end = 2 * CGFloat(M_PI) * progress + start
            
            //添加曲线
            let path = UIBezierPath(arcCenter: center, radius: r, startAngle: start, endAngle: end, clockwise: true)
            //增加指向圆心的路径
            path.addLineToPoint(center)
            
            //关闭路径
            path.closePath()
            
            UIColor(white: 0.0, alpha: 0.5).setFill()
            
            path.stroke()
            print("\(rect),\(progress)")
        }
    }
}
